package com.fruit.service.lightpay.impl;

import java.io.PrintWriter;
import java.io.StringWriter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.fruit.mapper.lightpay.LightPayMapper;
import com.fruit.pojo.lightpay.LightPayException;
import com.fruit.util.DateUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * LightPayLogService
 *
 * @author shibeilei
 * @version 2017.12.06 10:45
 *
 */
@Slf4j
@Service
public class LightPayLogService {

	@Autowired
	private LightPayMapper lightPayMapper;

	/**
	 * 
	 * @param tradeId 唯一流水号ID
	 * @param serviceName 服务名称
	 * @param serviceState 服务状态
	 * @param cashierCode 收银编号
	 * @param userId 用户ID
	 * @param code 错误标识
	 * @param message 错误内容
	 */
	public void newSaveExceptionLightPay(String tradeId, String serviceName, String serviceState, String cashierCode,
			int userId, String code, String message) {
		try {
			log.info("[{}]-【收银异常日志】-【收银流水号：{}】", tradeId, cashierCode);
			LightPayException lpe = new LightPayException();
			lpe.setTradeId(tradeId);
			lpe.setServiceName(serviceName);
			lpe.setCashierCode(cashierCode);
			lpe.setUserId(userId);
			JSONObject paJson = new JSONObject();
			paJson.put("code", cashierCode);
			lpe.setInputParams(paJson.toString());
			lpe.setServiceState(serviceState);
			lpe.setErrorCode(code);
			lpe.setErrorMessage(message);
			lpe.setQueryTime(DateUtil.getTime());
			lightPayMapper.saveExceptionLightPay(lpe);
			log.info("[{}]-【收银异常日志】-【成功】", tradeId);
		} catch (Exception e) {
			log.error("[{}]-【收银异常日志】-【异常】------【{}】", tradeId, getStackTraceAsString(e));
		}
		log.info("[{}]-【收银异常日志】-【结束】", tradeId);

	}

	/**
	 * @param ex 异常
	 * @return 返回错误信息
	 */
	public String getStackTraceAsString(Throwable ex) {
		StringWriter stringWriter = new StringWriter();
		ex.printStackTrace(new PrintWriter(stringWriter));
		return stringWriter.toString();
	}

}
